package com.unipay.spring.service;

import com.unipay.spring.dao.BookDao;
import com.unipay.spring.service.impl.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;

/**
 * @BelongsProject: SSM
 * @Author: cmy
 * @CreateTime: 2023-01-18  10:00
 * @Description: TODO
 */
@Service
public class BookSreviceImpl implements BookService {

    @Autowired
    private BookDao bookDao;

//    @Transactional(timeout = 3)
//    @Transactional(noRollbackFor = ArithmeticException.class)
    @Transactional(noRollbackForClassName = "java.lang.ArithmeticException", propagation = Propagation.REQUIRES_NEW)
    @Override
    public void buyBook(Integer bookId, Integer userId) {
//        bookDao.buyBook(bookId, userId);
/*
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
*/
        // 1、查看图书价格
        Integer price = bookDao.getPriceByBookId(bookId);
        // 2、更新图书库存
        bookDao.updateStock(bookId);
        // 3、更新用户余额
        bookDao.updateBalance(userId, price);

//        System.out.println(1 / 0);
    }
}
